import { callChromeMethod } from "./com";

/**
 * 脚本全局缓存
 * 本地+后台同步
 */
export namespace UserCache {
    const CACHE_PREFIX = 'dog_val_';

    function getPrefix(){
        return CACHE_PREFIX + Dog.info.uuid + '_'
    }

    export function init() {
        for (const k in localStorage) {
            if (k.startsWith(getPrefix())) {
                localStorage.removeItem(k);
            }
        }
        const caches: ScriptResourceInfo[] = DogruntimeData['caches'] || [];
        for (const c of caches) {
            localStorage.setItem(getPrefix() + c.key, String(c.data));
        }
    }

    export function getValue(key: string, defaultValue?: string) {
        return localStorage.getItem(getPrefix() + key) || defaultValue
    }

    export function setValue(key: string, value: string | number) {
        localStorage.setItem(getPrefix() + key, String(value));
        return syncCaches();
    }

    export function deleteValue(key: string) {
        localStorage.removeItem(getPrefix() + key);
        return syncCaches();
    }

    export function listValues() {
        const data: { [k: string]: any } = {};
        for (const k in localStorage) {
            if (k.startsWith(getPrefix())) {
                data[k.replace(getPrefix(), '')] = localStorage.getItem(k);
            }
        }
        return data
    }

    function syncCaches() {
        const data = listValues();
        const caches: ScriptResourceInfo[] = [];
        const id = GM.info.uuid;
        for (const k in data) {
            caches.push({
                key: k,
                data: data[k],
                type: 'cache',
                sid: id,
                resourceType: 'text/plain',
                id: ''
            })
        }

        return callChromeMethod('setValues', { id, caches });
    }
}